<template>
  <div class="container">
    <el-drawer
      append-to-body="true"
      v-loading="loading"
      title="用量明细"
      :visible.sync="drawer"
      direction="rtl"
      size="60%"
      :before-close="handleClose"
      @open="open"
    >
      <div class="box">
        <el-card style=" border: 1px solid #e6ebf5 !important;border-radius: 4px;">
          <div style="font-size:12px;">
            <!-- 基础信息 -->
            <div class="box1">
              <el-row :gutter="10">
                <el-col :span="12">租客姓名 : {{ singlePhaseData.membername}}</el-col>
                <el-col :span="12">设备编号 : {{singlePhaseData.sn}}</el-col>
                <el-col :span="12">联系方式 : {{singlePhaseData.membermobile}}</el-col>
                <el-col :span="12">房间信息 : {{singlePhaseData.roomname}}</el-col>
              </el-row>
            </div>
            <!-- 图 -->
            <div class="box2">
              <div>
                <span
                  :style="{color:(btnColor==1?'#409EFF':'#000')}"
                  class="box2_btn cursor"
                  @click="getTime(1)"
                >按日</span>
                <span
                  :style="{color:(btnColor==2?'#409EFF':'#000')}"
                  class="box2_btn cursor"
                  @click="getTime(2)"
                >按月</span>
                <el-date-picker
                  v-if="!isTimeShow"
                  class="box2_btn"
                  size="small"
                  @change="getData(2)"
                  v-model="value2"
                  type="month"
                  placeholder="选择月"
                  format="yyyy 年 MM 月"
                  value-format="yyyy-MM"
                ></el-date-picker>
                <el-date-picker
                  v-if="isTimeShow"
                  class="box2_btn"
                  size="small"
                  @change="getData(1)"
                  v-model="value1"
                  type="date"
                  placeholder="选择日期"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
                <el-button class="box2_btn" size="mini" type="primary" @click="handleExcel">导出</el-button>
              </div>
              <div class="box3">
                <div id="line-chart" style="margin-bottom:20px;"></div>
              </div>
            </div>
            <!-- 表格 -->
            <div class="box4">
              <avue-crud :data="devData" :option="option"></avue-crud>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import echarts from "echarts";
import { getDetailList } from "@/api/device/device";
import { dateFormat } from "@/util/date";
export default {
  props: ["drawer", "singlePhaseData"],
  data() {
    return {
      btnColor: 2,
      isTimeShow: false,
      loading: true,
      direction: "rtl",
      value2: dateFormat(new Date(), "yyyy-MM"),
      value1: dateFormat(new Date(), "yyyy-MM-dd"),
      devData: [],
      line1: {
        instance: null,
      },
      option: {
        menu: false,
        page: false,
        align: "center",
        menuAlign: "center",
        addBtn: false,
        column: [
          {
            label: "设备读数",
            prop: "dayFaeTotal",
          },
          {
            label: "读数时间",
            prop: "freezeTime",
          },
          {
            label: "时间段",
            prop: "period",
          },
          {
            label: "电量",
            prop: "power",
          },
        ],
      },
    };
  },
  mounted() {},
  beforeUpdate() {
    // this.$nextTick(() => {
    //   this.initLineChart();
    // });
  },
  methods: {
    handleExcel() {
      let opt = {
        title: "用电明细",
        column: [
          {
            label: "设备读数",
            prop: "dayFaeTotal",
          },
          {
            label: "读数时间",
            prop: "freezeTime",
          },
          {
            label: "时间段",
            prop: "period",
          },
          {
            label: "用量",
            prop: "power",
          },
        ],
        data: this.devData,
      };
      this.$export.excel({
        title: opt.title || new Date().getTime(),
        columns: opt.column,
        data: opt.data,
      });
    },
    getData(val) {
      this.loading = true;
      let data = {};
      if (val == 1) {
        // 日期
        data = {
          meterId: this.singlePhaseData.id,
          date: this.value1,
          datetype: 1,
        };
      } else if (val == 2) {
        //月
        data = {
          meterId: this.singlePhaseData.id,
          date: this.value2,
          datetype: 2,
        };
      }
      getDetailList(data).then((res) => {
        this.loading = false;
        console.log("getDetailList", res.data.data);
        const data = res.data.data;
        this.devData = data;
        let periodList = [];
        let powerList = [];
        let dayFaeTotalList = [];
        data.forEach((item) => {
          periodList.push(item.period);
          powerList.push(item.power);
          dayFaeTotalList.push(item.dayFaeTotal);
        });
        console.log("periodList", periodList);
        this.initLineChart({ periodList, powerList, dayFaeTotalList });
      });
    },
    open() {
      console.log("singlePhaseData", this.singlePhaseData);
      this.getData(this.btnColor);
    },
    getTime(val) {
      if (val == 1) {
        this.isTimeShow = true;
      } else {
        this.isTimeShow = false;
      }
      this.btnColor = val;
      this.getData(this.btnColor);
    },
    initLineChart(data) {
      var dom = document.getElementById("line-chart");
      this.line1.instance = echarts.init(dom, {
        renderer: "svg", // 支持 'canvas' 或者 'svg'
        width: null, // 可显式指定实例宽度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的宽度。
        height: null, // 可显式指定实例高度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的高度。
      });
      this.line1.instance.setOption(this.getLineOpt(data));
      var self = this;
      window.addEventListener("resize", function () {
        self.line1.instance.resize();
      });
    },
    getLineOpt(data) {
      var option = {};
      option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        // grid: {
        //   show: true,
        //   borderWidth: 0, //这样所有的坐标轴都没有了
        // },
        legend: {
          data: ["蒸发量"],
        },
        xAxis: [
          {
            type: "category",
            data: data.periodList,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: {
          type: "value",
          name: "电量",
          min: 0,
          interval: 50,
          axisLabel: {
            formatter: "{value}",
            interval: 6,
          },
        },
        series: [
          {
            name: "电量",
            type: "line",
            data: data.powerList,
          },
        ],
      };
      return option;
    },
    handleClose(done) {
      this.$emit("update:drawer", false);
      done();
    },
  },
};
</script>

<style scoped lang='scss'>
.box4 {
  padding-bottom: 50px;
  /deep/.avue-crud__menu {
    visibility: hidden;
    // display: none;
  }
}
.box {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  padding: 16px;
  overflow: auto;
}

.box1 {
  border-bottom: 1px solid #ccc;
}

.box2 {
  padding-top: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ccc;

  .box2_btn {
    margin-left: 20px;
  }
}

.box3 {
  margin-top: 30px;
  border-top: 1px solid #ccc;
  height: 330px;
  #line-chart {
    width: 100%;
    height: 330px;
  }
}
.cursor {
  cursor: pointer;
}
</style>